package com.lagou.boot;

import com.alibaba.fastjson.JSON;
import com.lagou.proto.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;

import java.nio.ByteBuffer;


public class NettyServerDecoder extends LengthFieldBasedFrameDecoder {


    public NettyServerDecoder() {
        super(Integer.MAX_VALUE, 0, 4, 0, 4);
    }

    @Override
    public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        ByteBuf frame = null;
        try {
            frame = (ByteBuf) super.decode(ctx, in);
            if (null == frame) {
                return null;
            }

            ByteBuffer byteBuffer = frame.nioBuffer();
            int length = byteBuffer.limit();
            byte[] data = new byte[length];
            byteBuffer.get(data);

            return JSON.parseObject(data, RpcRequest.class);
        } catch (Exception e) {
            e.printStackTrace();
            ctx.channel().close();
        } finally {
            if (null != frame) {
                frame.release();
            }
        }
        return null;
    }

}
